/**
 * Created by xiejinwei on 2017/2/28.
 */
//初始化布局
initLayout();
//初始化编辑器
var editor = ace.edit("editor");
editor.setOptions({
    enableBasicAutocompletion: true,
    enableSnippets: true,
    enableLiveAutocompletion: true
});
//默认主题
editor.setTheme("ace/theme/xcode");
//默认编辑器编程语言模式
editor.session.setMode("ace/mode/sql");
//自动适应大小
editor.resize();

//运行快捷键
editor.commands.addCommand({
    name: 'exec',
    bindKey: {win: 'Alt-R', mac: 'Alt-R'},
    exec: function (editor) {
        exec(editor);
    },
    readOnly: false // 如果不需要使用只读模式，这里设置false
});

//保存快捷键
editor.commands.addCommand({
    name: 'save',
    bindKey: {win: 'Alt-S', mac: 'Alt-S'},
    exec: function (editor) {
        save(editor);
    },
    readOnly: false // 如果不需要使用只读模式，这里设置false
});
//重新加载文件
editor.commands.addCommand({
    name: 'loadFile',
    bindKey: {win: 'Alt-L', mac: 'Alt-L'},
    exec: function (editor) {
        loadFile();
    },
    readOnly: false // 如果不需要使用只读模式，这里设置false
});
//重命名文件
editor.commands.addCommand({
    name: 'renameFile',
    bindKey: {win: 'Alt-Shift+R', mac: 'Alt-Shift+R'},
    exec: function (editor) {
        renameFile();
    },
    readOnly: false // 如果不需要使用只读模式，这里设置false
});
//删除文件
editor.commands.addCommand({
    name: 'deletFile',
    bindKey: {win: 'Alt-Shift-D', mac: 'Alt-Shift-D'},
    exec: function (editor) {
        deletFile();
    },
    readOnly: false // 如果不需要使用只读模式，这里设置false
});
//初始化布局
function initLayout() {
    var sourceTree = $("#sourceTree");
    var sqlEdit = $("#sqlEdit");
    var consoleAndResult = $("#consoleAndResult");
    var lengthwaysExpander = $("#lengthwaysExpander");
    var lengthwaysExpanderWidth = lengthwaysExpander.width();
    var win = $(window);
    var winHeight = win.height();
    var winWidth = win.width();
    var diffWidth = winWidth - lengthwaysExpanderWidth;
    var sourceTreeWidth = 410;//左侧默认宽度
    sourceTree.width(sourceTreeWidth);
    sqlEdit.width(diffWidth - sourceTreeWidth);
    consoleAndResult.width(diffWidth - sourceTreeWidth);
    lengthwaysExpander.height(winHeight);
    sourceTree.height(winHeight);
    $("#editor").height(winHeight - 30);
    //设置可自由改变大小
    var src_posi_Y = 0, dest_posi_Y = 0, move_Y = 0, destHeight = 30, src_posi_X = 0, dest_posi_X = 0, move_X = 0;
    var minWidthOrHeight = 50, is_mouse_down = false, isLengthwaysExpander = false, isCrosswiseExpander = false;
    //左右拖动
    $("#crosswiseExpander").mousedown(function (e) {
        src_posi_Y = e.pageY;
        is_mouse_down = true;
        isLengthwaysExpander = false;
        isCrosswiseExpander = true;
    });
    //上下拖动
    $("#lengthwaysExpander").mousedown(function (e) {
        src_posi_X = e.pageX;
        is_mouse_down = true;
        isLengthwaysExpander = true;
        isCrosswiseExpander = false;
    })
    //绑定拖动事件
    $(document).bind("click mouseup", function (e) {
        if (is_mouse_down) {
            is_mouse_down = false;
        }
    }).mousemove(function (e) {
        if (isLengthwaysExpander == true && isCrosswiseExpander == false) {//左右拖动
            dest_posi_X = e.pageX;
            move_X = src_posi_X - dest_posi_X;
            src_posi_X = dest_posi_X;
            if (is_mouse_down) {
                var sourceTree = $("#sourceTree");
                console.log($(window).width());
                var winWidth = $(window).width();
                var sourceTreeWidth = sourceTree.width() - move_X;
                if (sourceTreeWidth > winWidth - minWidthOrHeight || sourceTreeWidth < minWidthOrHeight) {
                    return;
                }
                var sqlEdit = $("#sqlEdit");
                var consoleAndResult = $("#consoleAndResult");
                sourceTree.width(sourceTreeWidth);
                sqlEdit.width(sqlEdit.width() + move_X);
                consoleAndResult.width(consoleAndResult.width() + move_X);
            }
        } else if (isLengthwaysExpander == false && isCrosswiseExpander == true) {//上下拖动
            dest_posi_Y = e.pageY;
            move_Y = src_posi_Y - dest_posi_Y;
            src_posi_Y = dest_posi_Y;
            destHeight = $("#consoleAndResult").height() + move_Y;
            if (is_mouse_down) {
                var winHeight = $(window).height();
                var $edit = $("#editor");
                var maxHeight = winHeight - minWidthOrHeight;
                $("#consoleAndResult").css("height", destHeight > minWidthOrHeight ? (destHeight > maxHeight ? maxHeight : destHeight) : minWidthOrHeight);
                $edit.height(winHeight - $("#consoleAndResult").height());
            }
        }
    });
}
//自动补全设置
function setCompleteData(data) {
    var langTools = ace.require("ace/ext/language_tools");
    langTools.addCompleter({
        getCompletions: function (editor, session, pos, prefix, callback) {
            if (prefix.length === 0) {
                return callback(null, []);
            } else {
                return callback(null, data);
            }
        }
    });
};
//设置编辑器字体大小
function setEditFontSize(fontSize) {
    $("#editor").css("fontSize", fontSize);
}

//设置编辑器主题
function setEditTheme(theme) {
    editor.setTheme("ace/theme/" + theme);
}

//设置编辑器主题
function setEditMode(mode) {
    editor.session.setMode("ace/mode/" + mode);
}

function loadFile() {
    if (loadSelectFile) {
        if (typeof loadSelectFile === "function") {
            loadSelectFile(sql, showFileContent);
        } else if (typeof getTopWin()[loadSelectFile] === "function") {
            getTopWin()[loadSelectFile](showFileContent);
        }
    }
    /**
     * 显示文件内容
     * @param fileContent 文件内容
     */
    function showFileContent(fileContent) {
        editor.setValue(fileContent);
    }
}
//重命名文件
function renameFile() {
    if (renameFileCallback) {
        if (typeof renameFileCallback === "function") {
            renameFileCallback();
        } else if (typeof getTopWin()[renameFileCallback] === "function") {
            getTopWin()[renameFileCallback]();
        }
    }
}
//删除文件
function deletFile() {
    if (deletFileCallback) {
        if (typeof deletFileCallback === "function") {
            deletFileCallback();
        } else if (typeof getTopWin()[deletFileCallback] === "function") {
            getTopWin()[deletFileCallback]();
        }
    }
}

//运行
function exec() {
    var sql = editor.getValue();
    console.log("执行sql:" + sql);
    if (executeCallback) {
        if (typeof executeCallback === "function") {
            executeCallback(sql, showResult);
        } else if (typeof getTopWin()[executeCallback] === "function") {
            getTopWin()[executeCallback](sql, showResult);
        }
    }
    /**
     * 执行结果回调
     * @param resultHtml 执行结果
     */
    function showResult(resultHtml) {
        $("#consoleAndResult .console").html(resultHtml);
    }
}

//保存
function save() {
    var content = editor.getValue();
    console.log("保存内容:" + content);
    if (saveCallback) {
        if (typeof saveCallback === "function") {
            saveCallback(content);
        } else if (typeof getTopWin()[saveCallback] === "function") {
            getTopWin()[saveCallback](content);
        }
    }
}